package com.trailer.base.base

import android.content.Context
import androidx.recyclerview.widget.RecyclerView
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.module.DraggableModule
import com.chad.library.adapter.base.module.LoadMoreModule
import com.chad.library.adapter.base.viewholder.BaseViewHolder
import com.hwangjr.rxbus.RxBus
import com.trailer.base.R
import com.trailer.base.utils.Toasts
import com.trailer.base.view.BView
import com.trailer.base.view.BaseView

abstract class BAdapter<T, K : BaseViewHolder> : BaseQuickAdapter<T, K>, BaseView, LoadMoreModule, DraggableModule {

    override fun context(): Context? {
        return context
    }

    constructor(layoutResId: Int) : super(layoutResId) {
        register()
    }

    constructor(layoutResId: Int, data: MutableList<T>?) : super(layoutResId, data) {
        register()
    }

    constructor(
            layoutResId: Int,
            draggable: Boolean = false,
            data: MutableList<T>? = null
    ) : super(layoutResId, data) {
        register()
        if (draggable) {
            draggableModule.isDragEnabled = true
            draggableModule.isSwipeEnabled = true
            draggableModule.isDragOnLongPressEnabled = false
            draggableModule.toggleViewId = R.id.img_sort
        }
    }

    override fun view(): BView? {
        return if (context is BView) {
            context as BView
        } else null
    }


    override fun onDetachedFromRecyclerView(recyclerView: RecyclerView) {
        super.onDetachedFromRecyclerView(recyclerView)
        unRegister()
    }

    override fun toast(msg: String?) {
        Toasts.toast(context, msg)
    }

    override fun toast(msgID: Int) {
        toast(context.getString(msgID))
    }

    fun clearList() {
        data.clear()
        notifyDataSetChanged()
    }

    override val isRxbus: Boolean
        get() = false

    final override fun register() {
        if (isRxbus) {
            RxBus.get().register(this)
        }
    }

    override fun unRegister() {
        if (isRxbus) {
            RxBus.get().unregister(this)
        }
    }
}
